import re
import random

from celery.result import AsyncResult
from django.shortcuts import render

# Create your views here.
from rest_framework_jwt.views import ObtainJSONWebToken
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,ListAPIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import CustomeSerializer, RegisterModelSerializer, MyOrderModelSerializer
from .utils import get_user_obj
from . import models
from luffyapi.settings import contains
from luffyapi.libs.ronglian_sms_sdk.sms import send_message
from django.conf import settings
from order.models import Order
from rest_framework.permissions import IsAuthenticated


class MyOrderView(ListAPIView):
	permission_classes = [IsAuthenticated,]
	serializer_class = MyOrderModelSerializer

	def get_queryset(self):
		return Order.objects.filter(user=self.request.user)


class CustomLoginView(ObtainJSONWebToken):
	serializer_class = CustomeSerializer


class CheckPhoneNumber(APIView):

	def get(self,request):
		phone_number = request.GET.get('phone')
		if not re.match('^1[3-9][0-9]{9}$',phone_number):
			return Response({'error_msg':'手机号格式有误,请重新输入'},status=status.HTTP_400_BAD_REQUEST)

		ret = get_user_obj(phone_number)
		if ret:
			return Response({'error_msg':'手机号已被注册,请换个手机号'}, status=status.HTTP_400_BAD_REQUEST)

		return Response({'msg':'ok'})

class RegisterView(CreateAPIView):
	queryset = models.User.objects.all()
	serializer_class = RegisterModelSerializer


import logging
logger = logging.getLogger('django')
from django_redis import get_redis_connection
class GetSMSCodeView(APIView):
	def get(self,request,phone):
		# 验证是否已经发送过短信了
		conn = get_redis_connection('sms_code')
		ret = conn.get('mobile_interval_%s'%phone)

		if ret:
			return Response({'msg':'60秒内已经发送过了，别瞎搞'}, status=status.HTTP_400_BAD_REQUEST)

		# 生成验证码
		sms_code = "%06d" % random.randint(0,999999)

		# 保存验证码
		conn.setex('mobile_%s'%phone,contains.SMS_CODE_EXPIRE_TIME,sms_code)

		conn.setex('mobile_interval_%s'%phone,contains.SMS_CODE_INTERVAL_TIME,sms_code)

		#  发送验证码

		# ret = send_message(settings.SMS_INFO.get('TID'),phone,(sms_code,contains.SMS_CODE_INTERVAL_TIME))
		#
		# if not ret:
		#     logger.error('{}手机号发送失败'.format(phone))
		#     return Response({'msg':'短信发送失败,请联系管理员'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

		from mycelery.sms.tasks import sms_codes
		sms_codes.delay(phone, sms_code)
		# ret = sms_codes.delay(phone,sms_code)
		# async_task = AsyncResult(id=ret.id, app=sms_codes)
		# result = async_task.get()
		# print('xxxxxxx>>>>',result)

		return Response({'msg':'ok'})

